package com.stx.jeepay.payment.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.jeepay.core.entity.TransferOrderEntity;
import com.stx.jeepay.core.service.TransferOrderService;
import com.stx.jeepay.payment.service.TransferOrderReissueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 转账补单定时任务
 */
@Slf4j
@Component
public class TransferOrderReissueTask {

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    @Autowired
    private TransferOrderService transferOrderService;
    @Autowired
    private TransferOrderReissueService transferOrderReissueService;

    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void start() {
        //查询条件：
        LambdaQueryWrapper<TransferOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TransferOrderEntity::getState, TransferOrderEntity.STATE_ING);
        queryWrapper.ge(TransferOrderEntity::getCreatedAt, DateUtil.offsetMinute(new Date(), -1));

        int currentPageIndex = 1; //当前页码

        while (true) {
            try {
                IPage<TransferOrderEntity> iPage =
                        transferOrderService.page(new Page<>(currentPageIndex, QUERY_PAGE_SIZE), queryWrapper);

                if(iPage == null || iPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询;
                    break;
                }

                for(TransferOrderEntity transferOrder: iPage.getRecords()){
                    transferOrderReissueService.processOrder(transferOrder);
                }

                //已经到达页码最大量，无需再次查询
                if(iPage.getPages() <= currentPageIndex){
                    break;
                }
                currentPageIndex++;
            } catch (Exception e) {
                log.error("error", e);
                break;
            }
        }
    }
}
